//
//  SFGiftThatCollectionViewCell.m
//  GiftThat
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "SFGiftThatCollectionViewCell.h"
#import "SFGiftSayScrollModel.h"
#import "SDCycleScrollView.h"
#import "SFSelectionCellModel.h"
#import "SFGiftThatTableViewCell.h"
#import "SFGiftLBoViewController.h"
#import "SFUnderLBoModel.h"
#import "SFUnderLBoCollectionViewCell.h"
@interface SFGiftThatCollectionViewCell ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *scrollArray;
@property (nonatomic, retain) NSMutableArray *buttonArray;
@property (nonatomic,strong) UIView  *Uview;
@property (nonatomic, retain) NSMutableArray *cellArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *cellString;
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property (nonatomic,strong) UIButton *button3;
@property (nonatomic,strong) UIButton *button4;
@property (nonatomic,strong) NSMutableArray *LBoarray;
@property (nonatomic,strong) SFGiftSayScrollModel *ScrollModel;
@property (nonatomic,strong) NSString *ShouYe;
@property (nonatomic,strong) UICollectionView *CollectionView;
@property (nonatomic,strong)  UICollectionViewFlowLayout *FlowLayout;
@property (nonatomic,strong) NSMutableArray *dataSource;

//-------刷新
//tableview方向判断
@property (nonatomic, assign) CGFloat contenty;
@property (nonatomic, strong) UIView *downLoad;
//box
@property (nonatomic, strong) UIImageView *box;
//heart
@property (nonatomic, strong) UIImageView *heart;
//boxarray
@property (nonatomic, strong) NSMutableArray *boxArray;


@end


@implementation SFGiftThatCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         self.ShouYe = [NSString stringWithFormat:SHOUYE,(long)self.page];
        
        self.backgroundColor = [UIColor whiteColor];
        [self GetTableview];
        [self GetData];
        [self scrollViewAndbutton];
        [self Getcollectionview];
        
        self.scrollArray = [NSMutableArray array];
        self.cellArray = [NSMutableArray array];
        self.LBoarray = [NSMutableArray array];
        self.dataSource = [NSMutableArray array];
        self.page = 0;
        
//        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
       
        //    下拉刷新
        self.downLoad = [[UIView alloc] initWithFrame:CGRectZero];
        self.downLoad.backgroundColor = [UIColor clearColor];
        [self addSubview:self.downLoad];
        [self bringSubviewToFront:self.downLoad];
        
        self.boxArray = [NSMutableArray arrayWithCapacity:0];
        self.box = [[UIImageView alloc] initWithFrame:CGRectZero];
        self.box.image = [UIImage imageNamed:@"box_01.png"];
        [self.downLoad addSubview:self.box];
        
        self.heart = [[UIImageView alloc] initWithFrame:CGRectZero];
        self.heart.image = [UIImage imageNamed:@"box_06"];
        self.heart.alpha = 0;
        [self.downLoad addSubview:self.heart];
        
        self.boxArray = [[NSMutableArray alloc] initWithCapacity:0];
        for (int i = 1; i < 6; i++) {
            NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
            UIImage *image = [UIImage imageNamed:str];
            [self.boxArray addObject:image];
        }
        for (int i = 0; i < 30; i++) {
            UIImage *image = [UIImage imageNamed:@"box_05.png"];
            [self.boxArray addObject:image];
        }
        for (int i = 4; i > 0; i--) {
            NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
            UIImage *image = [UIImage imageNamed:str];
            [self.boxArray addObject:image];
        }

        
    }
    return self;
}


-(void)GetData{
 
 //scrollerView上的数据
    [CXNetWorkTool getWithUrl:kGiftSaySelectionScrollGETURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
       
         NSArray *array = [[NSArray alloc]initWithArray:[[result objectForKey:@"data"] objectForKey:@"banners"]];
        for (NSDictionary *dic in array) {
            SFGiftSayScrollModel *data = [[SFGiftSayScrollModel alloc]initWithDictionary:dic];
            if (data.target_id != NULL) {
                 [self.LBoarray addObject:data.target_id];
        
           
            [self.scrollArray addObject:data.image_url];
          
            SDCycleScrollView *SDC = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.width , 180) imageURLStringsGroup:self.scrollArray];
             SDC.carouseType = suckEffect;
            SDC.delegate = self;
            [self.Uview addSubview:SDC];
        }
        }
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        
    }];
    [CXNetWorkTool getWithUrl:@"http://api.liwushuo.com/v2/secondary_banners?gender=1&generation=1" parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSArray *array = result[@"data"][@"secondary_banners"];
        for (NSDictionary *dic in array) {
           SFUnderLBoModel *UnderLBoModel = [[SFUnderLBoModel alloc]initWithDictionary:dic];
       
           [self.dataSource  addObject:UnderLBoModel];
    }
    [self.CollectionView reloadData];
    } fail:^(NSError *result) {
    
}];
//    首页
    
    [CXNetWorkTool getWithUrl:self.ShouYe parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSArray *array = [NSArray arrayWithArray:[[result objectForKey:@"data"] objectForKey:@"items"]];
         self.cellString = [[[result objectForKey:@"data"] objectForKey:@"paging"] objectForKey:@"next_url"];
        for (NSDictionary *dic in array) {
            SFSelectionCellModel *data = [[SFSelectionCellModel alloc]initWithDictionary:dic];
    
            [self.cellArray addObject:data];
         
        }
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        
    }];
    
}

-(void)GetTableview{
    self.tableView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
  
    [self.tableView registerClass:[SFGiftThatTableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self addSubview:self.tableView];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(DidPress) name:@"Refresh" object:nil];
}

-(void)DidPress{
    [self.tableView reloadData];
}

-(void)Getcollectionview{
    self.FlowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    self.FlowLayout.minimumInteritemSpacing = 5;
    self.FlowLayout.minimumLineSpacing = 7;
    self.FlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.CollectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:self.FlowLayout];
    self.CollectionView.delegate = self;
    self.CollectionView.dataSource = self;
    self.CollectionView.bounces = NO;
    self.CollectionView.showsHorizontalScrollIndicator = NO;
    self.CollectionView.backgroundColor = [UIColor whiteColor];
    [self.CollectionView registerClass:[SFUnderLBoCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellIdentifier"];
    [self.Uview addSubview:self.CollectionView];
}
#pragma tableView代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SFGiftThatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    if (self.cellArray.count > indexPath.row) {
         [cell setSelectionCellModel:self.cellArray[indexPath.row]];
    }
   
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
//tableview点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self.delegate tableviewJump:[NSString stringWithFormat:@"%@",[self.cellArray[indexPath.row] url]]];
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 280;
}
#pragma collectionView代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SFUnderLBoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellIdentifier" forIndexPath:indexPath];
    if (self.dataSource.count > indexPath.row) {
        [cell setUnderLBoModel:self.dataSource[indexPath.row]];

    }
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SFUnderLBoModel *UnderLBoModel = self.dataSource[indexPath.row];
 
    [self.delegate UnderLBo:UnderLBoModel.target_url];
    
    
}
//创建轮播图和下面的button放在一个view上
-(void)scrollViewAndbutton{
    self.Uview = [[UIView alloc]init];
    self.Uview.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.Uview;
}

-(void)layoutSubviews{
    [super layoutSubviews];
   
    self.Uview.frame = CGRectMake(0,0, self.width, 280);
    self.tableView.frame = CGRectMake(0, 5, self.width, self.height - 80);
    self.CollectionView.frame = CGRectMake(5, 190, self.width - 10, 80);
    self.FlowLayout.itemSize = CGSizeMake((self.width - 25) / 4 , 80);
    
   
     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
     [center addObserver:self selector:@selector(receiveNotification) name:@"Color" object:nil];
}
-(void)receiveNotification{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        
        self.Uview.backgroundColor = [UIColor colorWithRed:37 / 255.0 green:36 / 255.0 blue:40 / 255.0 alpha:1.0];
        self.CollectionView.backgroundColor = [UIColor colorWithRed:37 / 255.0 green:36 / 255.0 blue:40 / 255.0 alpha:1.0];
        
        
    }else{
        
        self.Uview.backgroundColor = [UIColor whiteColor];
        self.CollectionView.backgroundColor = [UIColor whiteColor];
        
        
    }
}

//轮播图点击事件
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    for (int i = 0; i < self.LBoarray.count; i++) {
        self.ScrollModel = self.LBoarray[index];
    }
 
    [self.delegate LBoPassByValue:self.ScrollModel];
    
}
////下拉刷新
//-(void)loadNewData{
//
//    [self.cellArray removeAllObjects];
////    [self.tableView.mj_header endRefreshing];
//    [CXNetWorkTool getWithUrl:self.ShouYe parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
//        NSArray *array = [NSArray arrayWithArray:[[result objectForKey:@"data"] objectForKey:@"items"]];
//        self.cellString = [[[result objectForKey:@"data"] objectForKey:@"paging"] objectForKey:@"next_url"];
//        for (NSDictionary *dic in array) {
//            SFSelectionCellModel *data = [[SFSelectionCellModel alloc]initWithDictionary:dic];
//            [self.cellArray addObject:data];
//            
//        }
//        [self.tableView reloadData];
//    } fail:^(NSError *error) {
//        
//    }];
//}
//上拉加载
-(void)loadMore{
    self.page += 20;
    self.ShouYe = [NSString stringWithFormat:SHOUYE,(long)self.page];

    [CXNetWorkTool getWithUrl:self.ShouYe parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSArray *array = [NSArray arrayWithArray:[[result objectForKey:@"data"] objectForKey:@"items"]];
        self.cellString = [[[result objectForKey:@"data"] objectForKey:@"paging"] objectForKey:@"next_url"];
        for (NSDictionary *dic in array) {
            SFSelectionCellModel *data = [[SFSelectionCellModel alloc]initWithDictionary:dic];
            [self.cellArray addObject:data];
            
        }
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        
    }];

    [self.tableView.mj_footer endRefreshing];
}

#pragma mark -- 上拉加载
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //    if (scrollView.contentOffset.y > self.contenty) {
    //        NSLog(@"加载数据");
    //        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
    //            //加载更多数据
    //            if (scrolltimes == 0) {
    //                numOfAll = numOfAll + 20;
    //                [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", numOfAll] withGeneration:@"1"];
    //                scrolltimes = 1;
    //            }
    //        }
    //    }
    if (scrollView.contentOffset.y < 0) {
        self.downLoad.frame = CGRectMake(0, 33, self.width, 0 - scrollView.contentOffset.y);
        self.box.frame = CGRectMake((self.width - self.width / 10) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23, self.width / 10, self.width / 10 / 1.23);
        self.heart.frame = CGRectMake((self.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23, self.box.width / 4 * 2, self.box.height / 4 * 3);
    }
}


#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                [UIView setAnimationDelay:0];
                self.heart.frame = CGRectMake((self.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23 - self.box.height / 4 * 3, self.box.width / 4 * 2, self.box.height / 4 * 3);
                self.heart.alpha = 1;
            } completion:^(BOOL finished) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
                    self.heart.alpha = 0;
                });
            }];
        });
        
        [self.box setAnimationImages:self.boxArray];
        [self.box setAnimationDuration:2];
        [self.box setAnimationRepeatCount:1];
        [self.box startAnimating];
        
        [self.dataSource removeAllObjects];
        
        [self.cellArray removeAllObjects];
        //    [self.tableView.mj_header endRefreshing];
        [CXNetWorkTool getWithUrl:self.ShouYe parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            NSArray *array = [NSArray arrayWithArray:[[result objectForKey:@"data"] objectForKey:@"items"]];
            self.cellString = [[[result objectForKey:@"data"] objectForKey:@"paging"] objectForKey:@"next_url"];
            for (NSDictionary *dic in array) {
                SFSelectionCellModel *data = [[SFSelectionCellModel alloc]initWithDictionary:dic];
                [self.cellArray addObject:data];
                
            }
            [self.tableView reloadData];
        } fail:^(NSError *error) {
            
        }];
        //        [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", 0] withGeneration:@"1"];
    }
    
}


@end
